/**
 * Created by henian.xu on 2019/3/19.
 * 设备检查
 */

export const Device = (function Device() {
  const { platform } = window.navigator;
  const ua = window.navigator.userAgent;
  const docEl = document.documentElement;

  const device = {
    ua,
    ios: false,
    android: false,
    androidChrome: false,
    desktop: false,
    windowsPhone: false,
    iphone: false,
    iphoneX: false,
    ipod: false,
    ipad: false,
    edge: false,
    ie: false,
    firefox: false,
    macos: false,
    windows: false,
    cordova: !!(window.cordova || window.phonegap),
    phonegap: !!(window.cordova || window.phonegap),
    electron: false,
    webview: false,
    standalone: false,
    statusbar: false,
    weixin: false,
    windowWeixin: false,
    weixinMiniProgram: false,
    pixelRatio: 1,
    os: '',
    osVersion: null,
    needsStatusbarOverlay: () => false,
    width: docEl.clientWidth,
    height: docEl.clientHeight,
    documentElement: docEl,
  };

  const screenWidth = window.screen.width;
  const screenHeight = window.screen.height;

    const windowsPhone = ua.match(/(Windows Phone);?[\s\/]+([\d.]+)?/); // eslint-disable-line
    const android = ua.match(/(Android);?[\s\/]+([\d.]+)?/); // eslint-disable-line
  const ipad = ua.match(/(iPad).*OS\s([\d_]+)/);
  const ipod = ua.match(/(iPod)(.*OS\s([\d_]+))?/);
  const iphone = !ipad && ua.match(/(iPhone\sOS|iOS)\s([\d_]+)/);
  const iphoneX =
    iphone &&
    ((screenWidth === 375 && screenHeight === 812) || // X/XS
      (screenWidth === 414 && screenHeight === 896)); // XR / XS Max
  const ie = ua.indexOf('MSIE ') >= 0 || ua.indexOf('Trident/') >= 0;
  const edge = ua.indexOf('Edge/') >= 0;
  const firefox = ua.indexOf('Gecko/') >= 0 && ua.indexOf('Firefox/') >= 0;
  const macos = platform === 'MacIntel';
  const windows = platform === 'Win32';
  const electron = ua.toLowerCase().indexOf('electron') >= 0;
  const weixin = !!ua.match(/MicroMessenger/);
  const windowWeixin = !!ua.match(/WindowsWechat/);
  const weixinMiniProgram = !!ua.match(/miniProgram/);

  device.ie = ie;
  device.edge = edge;
  device.firefox = firefox;
  device.weixin = weixin;
  device.windowWeixin = windowWeixin;

  // weixinMiniProgram
  if (!weixin && !weixinMiniProgram) {
    const { wx } = window;
    if (window.__wxjs_environment === 'miniprogram') {
      device.weixinMiniProgram = true;
    } else if (wx && wx.miniProgram) {
      // 这是个异步的过程，原理是 WeixinJSBridgeReady 事件中判断 window.__wxjs_environment === "miniprogram"
      wx.miniProgram.getEnv((res) => {
        device.weixinMiniProgram = res.miniprogram;
      });
    } else {
      device.weixinMiniProgram = false;
    }
  } else {
    device.weixinMiniProgram = weixinMiniProgram;
  }
  console.log('first weixinMiniProgram: ', device.weixinMiniProgram);

  // Windows
  if (windowsPhone) {
    device.os = 'windowsPhone';
    // eslint-disable-next-line prefer-destructuring
    device.osVersion = windowsPhone[2];
    device.windowsPhone = true;
  }
  // Android
  if (android && !windows) {
    device.os = 'android';
    // eslint-disable-next-line prefer-destructuring
    device.osVersion = android[2];
    device.android = true;
    device.androidChrome = ua.toLowerCase().indexOf('chrome') >= 0;
  }
  if (ipad || iphone || ipod) {
    device.os = 'ios';
    device.ios = true;
  }
  // iOS
  if (iphone && !ipod) {
    device.osVersion = iphone[2].replace(/_/g, '.');
    device.iphone = true;
    device.iphoneX = !!iphoneX;
  }
  if (ipad) {
    device.osVersion = ipad[2].replace(/_/g, '.');
    device.ipad = true;
  }
  if (ipod) {
    device.osVersion = ipod[3] ? ipod[3].replace(/_/g, '.') : null;
    device.iphone = true;
  }
  // iOS 8+ changed UA
  if (device.ios && device.osVersion && ua.indexOf('Version/') >= 0) {
    if (device.osVersion.split('.')[0] === '10') {
      // eslint-disable-next-line prefer-destructuring
      device.osVersion = ua.toLowerCase().split('version/')[1].split(' ')[0];
    }
  }

  // Webview
  const webView =
    !!(
      (iphone || ipad || ipod) &&
      (ua.match(/.*AppleWebKit(?!.*Safari)/i) || window.navigator.standalone)
    ) ||
    (window.matchMedia &&
      window.matchMedia('(display-mode: standalone)').matches);
  device.webview = webView;
  device.standalone = webView;

  // Desktop
  device.desktop =
    !(device.ios || device.android || device.windowsPhone || device.weixin) ||
    electron;
  if (device.desktop) {
    device.electron = electron;
    device.macos = macos;
    device.windows = windows;
  }

  // Meta statusbar
  const metaStatusbar = document.querySelector(
    'meta[name="apple-mobile-web-app-status-bar-style"]',
  );

  // Check for status bar and fullscreen app mode
  device.needsStatusbarOverlay = function needsStatusbarOverlay() {
    if (device.desktop) return false;
    if (
      device.standalone &&
      device.ios &&
      metaStatusbar &&
      metaStatusbar.content === 'black-translucent'
    ) {
      return true;
    }
    if (
      (webView || (device.android && device.cordova)) &&
      window.innerWidth * window.innerHeight ===
        window.screen.width * window.screen.height
    ) {
      return !(
        device.iphoneX &&
        (window.orientation === 90 || window.orientation === -90)
      );
    }
    return false;
  };
  device.statusbar = device.needsStatusbarOverlay();

  // Pixel Ratio
  device.pixelRatio = window.devicePixelRatio || 1;

  // Export object
  return device;
})();

export default Device;
